package com.pencilisland.pay.core.mp.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pencilisland.pay.api.bean.constant.GoodsConstant;
import com.pencilisland.pay.api.bean.mp.core.CancelGoodsREQ;
import com.pencilisland.pay.api.bean.mp.core.CancelGoodsRES;
import com.pencilisland.pay.api.bean.mp.core.MessageRequest;
import com.pencilisland.pay.api.bean.mp.core.MessageResponse;
import com.pencilisland.pay.api.entity.GoodsEntity;
import com.pencilisland.pay.api.repository.GoodsRepository;
import com.pencilisland.pay.api.service.CacheService;
import com.pencilisland.pay.core.mp.service.MBService;

/**
 * 报文逻辑处理.撤销商品
 *
 * @author breeze
 */
@Service("MB_cancelGoods")
public class CancelGoodsMB implements MBService {
	@Autowired
	GoodsRepository goodsRepo;
	@Autowired
	CacheService cacheService;
	@Autowired
	ObjectMapper objectMapper;

	@Override
	public MessageResponse process(MessageRequest request) {
		CancelGoodsREQ requestBean = getRequestBody(request);

		GoodsEntity goods = goodsRepo.findByCode(requestBean.getCode());
		if (goods != null) {
			goods.setStatus(GoodsConstant.STATUS_0);
			goods.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
			goodsRepo.save(goods);
			
			cacheService.clearGoods(goods.getCode());
			cacheService.clearAllGoods();
		}

		CancelGoodsRES res = new CancelGoodsRES(true, null, "OK");
		return res;
	}

	public CancelGoodsREQ getRequestBody(MessageRequest request) {
		return objectMapper.convertValue(request.getBody(), CancelGoodsREQ.class);
	}

}
